<template>
  <div class="app-container">
    <!-- 统计信息展示 -->
    <div v-if="statisticsVisible" class="statistics-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-title">总区域数</div>
            <div class="stat-value">{{ regionStatistics.totalRegions }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-title">总点位数量</div>
            <div class="stat-value">{{ regionStatistics.totalNodes }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-title">总设备数量</div>
            <div class="stat-value">{{ regionStatistics.totalDevices }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-title">活跃设备</div>
            <div class="stat-value">{{ regionStatistics.activeDevices }}</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="区域名称" prop="regionName">
        <el-input
          v-model="queryParams.regionName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="3">
        <div style="display: flex; gap: 8px;">
          <el-button
            :type="viewMode === 'table' ? 'primary' : 'default'"
            plain
            @click="switchToTable"
          >表格视图</el-button>
          <el-button
            :type="viewMode === 'tree' ? 'primary' : 'default'"
            plain
            @click="switchToTree"
          >树形视图</el-button>
        </div>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="PieChart"
          @click="toggleStatistics"
          v-hasPermi="['manage:region:statistics']"
        >统计信息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:region:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:region:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:region:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:region:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格视图 -->
    <el-table v-if="viewMode === 'table'" v-loading="loading" :data="regionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="区域名称" align="center" prop="regionName" />
      <el-table-column label="点位数量" align="center" prop="nodeCount" />
      <el-table-column label="备注说明" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['manage:region:edit']">修改</el-button>
          <el-button link type="primary"  @click="handleDelete(scope.row)" v-hasPermi="['manage:region:remove']">删除</el-button>
          <el-button link type="primary"  @click="handleGetRegionInfo(scope.row)" v-hasPermi="['manage:node:list']">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-if="viewMode === 'table'"
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    
    <!-- 树形视图 -->
    <div v-else-if="viewMode === 'tree'" class="tree-container">
      <el-tree
        v-loading="loading"
        :data="regionTreeData"
        :props="treeProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span class="node-count">点位数量: {{ data.nodeCount || 0 }}</span>
            <span class="node-actions">
              <el-button
                v-hasPermi="['manage:region:edit']"
                type="text"
                size="small"
                @click.stop="handleUpdate(data)"
              >修改</el-button>
              <el-button
                v-hasPermi="['manage:region:remove']"
                type="text"
                size="small"
                @click.stop="handleDelete(data)"
              >删除</el-button>
              <el-button
                v-hasPermi="['manage:node:list']"
                type="text"
                size="small"
                @click.stop="handleGetRegionInfo(data)"
              >查看详情</el-button>
            </span>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 添加或修改区域管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="regionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域名称" prop="regionName">
          <el-input v-model="form.regionName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="父级区域" prop="parentId">
          <el-cascader
            v-model="selectedParentRegion"
            :options="parentRegionTree"
            :props="cascaderProps"
            placeholder="请选择父级区域"
            clearable
            @change="handleParentRegionChange"
            <!-- 移除禁用属性，允许在修改模式下也能编辑父级区域 -->
          ></el-cascader>
          <div style="font-size: 12px; color: #606266; margin-top: 4px;">
            区域层级最多支持5级
          </div>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情对话框 -->
    <el-dialog title="区域详情" v-model="regionInfoOpen" width="500px" append-to-body>
         <el-form-item label="区域名称" prop="regionName" > 
          <el-input v-model="form.regionName" placeholder="请输入区域名称" disabled/>
        </el-form-item>
        <label>点位列表:</label>
        <el-table :data="nodeList" style="width: 100%">
          <el-table-column label="序号" type="index" align="center" prop="id" width="50"/>
          <el-table-column label="点位名称" align="center" prop="nodeName" />
          <el-table-column label="设备数量" align="center" prop="vmCount" />
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeRegionInfo">关闭</el-button>
          </div>
        </template>
      </el-dialog>

  </div>
</template>

<script setup name="Region">
import { listRegion, getRegion, delRegion, addRegion, updateRegion, getRegionTreeData, getRegionStatistics, getRegionTreeSelect, checkRegionLevel } from "@/api/manage/region";
import { listNode } from "@/api/manage/node";
import { loadAllParams } from "@/api/page";
const { proxy } = getCurrentInstance();

const regionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const viewMode = ref('table'); // 表格视图
const selectedParentRegion = ref([]); // 选中的父级区域
const regionTreeData = ref([]); // 树形数据
const treeProps = {
  label: 'regionName',
  children: 'children'
}; // 树形组件配置
// 父区域选择
const parentRegionOptions = ref([]);
// const parentRegionTree = ref([]); // 已在第274行定义，删除重复定义
const parentRegionProps = {
  label: 'regionName',
  value: 'id',
  children: 'children'
}; // 父区域选择配置
// 级联选择器配置
const cascaderProps = {
  label: 'regionName',
  value: 'id',
  children: 'children'
};
// 父级区域树形数据
const parentRegionTree = ref([]); // 取消注释，正确定义变量
// 最大层级限制
const MAX_LEVEL = 5;
// 统计信息
const regionStatistics = ref({
  totalRegions: 0,
  totalNodes: 0,
  totalDevices: 0,
  activeDevices: 0
});
const statisticsVisible = ref(false); // 统计信息可见性

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    regionName: null,
  },
  rules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注说明不能为空", trigger: "blur" }
    ],
    parentId: [
      { required: false, message: "请选择上级区域", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询区域管理列表 */
function getList() {
  loading.value = true;
  listRegion(queryParams.value).then(response => {
    regionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询区域树形数据 */
function getRegionTree() {
  loading.value = true;
  getRegionTreeData().then(response => {
    regionTreeData.value = response.data;
    loading.value = false;
  });
}

/** 切换统计信息显示/隐藏 */
function toggleStatistics() {
  statisticsVisible.value = !statisticsVisible.value;
  if (statisticsVisible.value) {
    // 默认显示所有区域的统计信息（传入null或不传入参数）
    fetchRegionStatistics();
  }
}

/** 获取区域统计信息 */
function fetchRegionStatistics(regionId = null) {
  loading.value = true;
  getRegionStatistics(regionId).then(response => {
    regionStatistics.value = response.data;
    loading.value = false;
  }).catch(error => {
    console.error('获取区域统计信息失败:', error);
    proxy.$modal.msgError('获取统计信息失败');
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    regionName: null,
    createTime: null,
    dateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    parentId: null
  };
  // 修复状态管理问题：重置选中的父级区域
  selectedParentRegion.value = [];
  proxy.resetForm("regionRef");
}

/** 加载父区域选择数据 */
function loadParentRegionOptions() {
  // 确保树形数据已经加载
  if (regionTreeData.value.length === 0 && viewMode.value !== 'tree') {
    getRegionTree();
  }
  // 如果是修改操作，需要排除当前区域及其子区域
  const excludeId = form.value.id || null;
  console.log('加载父区域数据，排除ID:', excludeId);
  getRegionTreeSelect({ excludeId }).then(response => {
    console.log('父区域数据获取成功:', response.data);
    
    // 修复数据格式问题：确保每个数据项都有正确的属性
    if (response.data && Array.isArray(response.data)) {
      parentRegionTree.value = response.data.map(item => ({
        id: item.id || '',
        label: item.regionName || item.label || '未命名区域',
        regionName: item.regionName || item.label || '未命名区域',
        children: item.children || [] // 确保children属性存在
      }));
    } else {
      parentRegionTree.value = [];
    }
    
    console.log('parentRegionTree处理后:', parentRegionTree.value);
    
    // 修复选择器不显示选中值的问题：如果有parentId，找到完整路径并设置selectedParentRegion
    if (form.value.parentId && parentRegionTree.value.length > 0) {
      const path = findRegionPath(parentRegionTree.value, form.value.parentId);
      if (path && path.length > 0) {
        selectedParentRegion.value = path;
      }
    }
  }).catch(error => {
    console.error('获取父区域数据失败:', error);
    parentRegionTree.value = []; // 出错时确保数据为空数组
  });
}

/** 递归查找区域完整路径 */
function findRegionPath(tree, targetId) {
  for (const node of tree) {
    if (node.id === targetId) {
      return [node.id]; // 找到目标节点，返回路径
    }
    if (node.children && node.children.length > 0) {
      const path = findRegionPath(node.children, targetId);
      if (path) {
        return [node.id, ...path]; // 找到子节点路径，添加当前节点ID
      }
    }
  }
  return null; // 未找到目标节点
}

// 切换到表格视图
function switchToTable() {
  viewMode.value = 'table';
  getList();
}

// 切换到树形视图
function switchToTree() {
  viewMode.value = 'tree';
  getRegionTree();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加区域管理";
  // 确保选择器状态正确初始化
  selectedParentRegion.value = [];
  // 加载父区域选项
  loadParentRegionOptions();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRegion(_id).then(response => {
    form.value = response.data;
    // 修复父级区域名称显示问题：当parentName为null时，设置默认值
    if (form.value.parentName === null || form.value.parentName === undefined) {
      form.value.parentName = '无父级区域';
    }
    // 确保选择器状态正确初始化
    selectedParentRegion.value = [];
    open.value = true;
    title.value = "修改区域管理";
    // 加载父区域选项
    loadParentRegionOptions();
  }).catch(error => {
    console.error('获取区域详情失败:', error);
    proxy.$modal.msgError('获取区域详情失败');
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["regionRef"].validate(valid => {
    if (valid) {
      // 如果选择了上级区域，进行层级检查
      if (form.value.parentId && form.value.parentId !== 'null') {
        checkRegionLevel(form.value.parentId, 5).then(response => {
          if (response.code === 200) {
            // 层级检查通过
            submitData();
          } else {
            // 层级检查失败
            proxy.$modal.msgError(response.msg || '区域层级已达到最大限制(5级)');
          }
        }).catch(error => {
          console.error('检查区域层级失败:', error);
          proxy.$modal.msgError('检查区域层级失败');
        });
      } else {
        // 没有选择上级区域，直接提交
        submitData();
      }
    }
  });
}

/** 提交数据 */
function submitData() {
  // 处理parentId为'null'的情况
  const submitForm = {
    ...form.value,
    parentId: form.value.parentId === 'null' ? null : form.value.parentId
  };
  
  if (submitForm.id != null) {
    updateRegion(submitForm).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      open.value = false;
      getList();
    }).catch(error => {
      console.error('修改区域失败:', error);
      proxy.$modal.msgError('修改失败，请重试');
    });
  } else {
    addRegion(submitForm).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList();
    }).catch(error => {
      console.error('新增区域失败:', error);
      proxy.$modal.msgError('新增失败，请重试');
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除区域管理编号为"' + _ids + '"的数据项？删除后，该区域下的所有子区域和关联数据可能会受到影响。').then(function() {
    return delRegion(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(error => {
    console.error('删除区域失败:', error);
    if (error.response && error.response.data && error.response.data.msg) {
      proxy.$modal.msgError(error.response.data.msg);
    } else {
      proxy.$modal.msgError('删除失败，请重试');
    }
  });
}



/** 查看详情按钮操作 */
const nodeList = ref([]);
const regionInfoOpen = ref(false);
function handleGetRegionInfo(row) {
  //查询区域信息
  reset();
  const _id = row.id
  getRegion(_id).then(response => {
    console.log(response.data);
    form.value = response.data;
    // 修复父级区域名称显示问题：当parentName为null时，设置默认值
    if (form.value.parentName === null || form.value.parentName === undefined) {
      form.value.parentName = '无父级区域';
    }
  }).catch(error => {
    console.error('获取区域详情失败:', error);
    proxy.$modal.msgError('获取区域详情失败');
  });
  //查询点位列表
  loadAllParams.regionId=row.id
  listNode(loadAllParams).then(response => {
    nodeList.value = response.rows;
  }).catch(error => {
    console.error('获取点位列表失败:', error);
    proxy.$modal.msgError('获取点位列表失败');
  });
  regionInfoOpen.value=true;
}



/** 父级区域选择变化处理 */
function handleParentRegionChange(value) {
  if (value && value.length > 0) {
    // 级联选择器的值是一个数组，最后一个元素是选中的父级区域ID
    form.value.parentId = value[value.length - 1];
  } else {
    form.value.parentId = null;
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/region/export', {
    ...queryParams.value
  }, `region_${new Date().getTime()}.xlsx`)
}


getList();
// 关闭区域详情对话框
function closeRegionInfo() {
  regionInfoOpen.value = false;
  reset(); // 重置状态，避免状态污染
}
</script>

<style scoped>
.tree-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  min-height: 400px;
}
.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 0;
}
.node-count {
  color: #606266;
  font-size: 12px;
  margin: 0 10px;
}
.node-actions {
  display: flex;
  gap: 5px;
}

/* 统计信息样式 */
.statistics-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-title {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}
</style>
